#include "client.h"

char global_token[512];

static int get_ser_fd(void);
//-1失败 0成功                                   
int login_register(){
    printf("\t*********欢迎来到躺平网盘*********\n");
    printf("\t请在以下方式中进行选择（请输入数字）：\n");
    printf("\t1.密码登录  2.注册  3.注销  5.退出\n");
    char buf[128] = { 0 };
    int num;
    printf("请输入你的选择：");
    fflush(stdout);
    read(STDIN_FILENO, buf, sizeof(buf));
    if(buf[1] != '\n'){
        printf("去你妈的，都告诉你了选择以下数字，你还乱搞，你是傻逼吗？\n给我滚蛋！！！！！\n");
        return -1;
    }else{
        buf[1] = '\0';
        num = atoi(buf);
    }
    if (num == 5){
        exit(0);
    }
    if(num > 3 || num <= 0){
        printf("哥们，数字输错了\n");
        return -1;
    }
    printf("----------------------------------\n");
    printf("请输入用户名（名字不能超过20字）：\n");
    bzero(buf, sizeof(buf));
    char name[25] = { 0 };
    read(STDIN_FILENO, buf, sizeof(buf));
    if(strlen(buf) >= 25){
        printf("你名字取这么长不要命了吗，滚蛋吧！！！\n");
        return -1;
    }else{
        strncpy(name, buf, strlen(buf) - 1);
    }
    printf("请输入密码（密码不能超过10位）:\n");
    bzero(buf, sizeof(buf));
    read(STDIN_FILENO, buf, sizeof(buf));
    char password[11] = { 0 };
    if(strlen(buf) >= 11){
        printf("怎么不听劝呢，看不见提示吗，没长眼睛是不是，滚！！！\n");
        return -1;
    }else{
        strncpy(password, buf, strlen(buf) - 1);
    }

    //-----------------------------------------

    int netFD = get_ser_fd();
    send(netFD, &num, sizeof(num), MSG_NOSIGNAL);
    send(netFD, name, sizeof(name), MSG_NOSIGNAL);
    send(netFD, password, sizeof(password), MSG_NOSIGNAL);

    int server_num;
    recv(netFD, &server_num, sizeof(int), MSG_WAITALL);
    if(num == 3){
        return server_num;
    }
    if(server_num == 0){
        //登录成功
        recv(netFD, global_token, sizeof(global_token), MSG_WAITALL);
        printf("token:%s\n", global_token);
        return netFD;
    }

    close(netFD);
    return -1;
}


static int get_ser_fd(void){
    int ser_fd = socket(AF_INET,SOCK_STREAM,0);
    ERROR_CHECK(ser_fd,-1,"socket");

    struct sockaddr_in ser_addr;
    ser_addr.sin_family = AF_INET;
    int ret = inet_pton(AF_INET,"127.0.0.1",&ser_addr.sin_addr);
    ERROR_CHECK(ret,-1,"inet_pton");
    ser_addr.sin_port = htons(atoi("8080"));

    ret = connect(ser_fd,(struct sockaddr*)&ser_addr,sizeof(ser_addr));
    ERROR_CHECK(ret,-1,"connect");

    return ser_fd;
}

